[id].ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { defineEventHandler, EventHandlerRequest } from 'h3';
  2. import { DB } from '~~/server/db/DB';
  3. import { createErrorResponse, createSuccessResponse, IResponse } from '~~/server/utils/response';
  4. import { IChannel } from '../channel/[id]';
  5. export interface IArticle {
  6. id: number;
  7. model_id: number;
  8. channel_id: number;
  9. title: string;
  10. desc: string;
  11. image: string,
  12. video?: string,
  13. images: string;
  14. seotitle: string;
  15. keywords: string;
  16. description: string;
  17. tags: string;
  18. diyname: string;
  19. publishtime: number;
  20. createtime: number;
  21. views: number;
  22. content: string;
  23. channel: IChannel;
  24. outlink?: string;
  25. }
  26. export default defineEventHandler<EventHandlerRequest, Promise<IResponse<IArticle>>>(async (event) => {
  27. try {
  28. const id = event.context.params?.id;
  29. if (!id)
  30. return createErrorResponse('分类ID不能为空');
  31. const article = await DB.table('pr_cms_archives')
  32. .where('id', id)
  33. .where('status', 'normal')
  34. .first();
  35. if (!article)
  36. return createErrorResponse('文章不存在');
  37. const channel = await DB.table('pr_cms_channel')
  38. .where('id', article.channel_id)
  39. .first();
  40. if (!channel)
  41. return createErrorResponse('分类不存在');
  42. article.channel = channel;
  43. // 2. 通过model_id从pr_cms_model表中获取table字段
  44. const model = await DB.table('pr_cms_model')
  45. .where('id', article.model_id)
  46. .select('table')
  47. .first();
  48. if (!model)
  49. return createErrorResponse('分类不存在');
  50. // 3. 通过table指定的表通过id查出content
  51. const content = await DB.table(`pr_${model.table}`)
  52. .where('id', id)
  53. .select('content')
  54. .first();
  55. // 4. 合并返回结果
  56. if (content && content['content']) {
  57. article.content = content['content'];
  58. }
  59. return createSuccessResponse(article);
  60. } catch (error) {
  61. return createErrorResponse(error);
  62. }
  63. });